package com.example.election;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

/***
 * 基于文件共享的锁
 */
@Service("shareFileElectionService")
public class ShareFileElectionServiceImpl implements ElectionService {

    Logger logger = LoggerFactory.getLogger(getClass());

    public static final String LOCK = "/lock/lock.lock";

    private FileChannel fileChannel;

    private FileLock lock;

    private RandomAccessFile file;

    private volatile boolean isStop = false;

    @Override
    public void doStart() {
        while (true) {
            try {
                file = new RandomAccessFile(getClass().getClassLoader().getResource("").getPath() + LOCK, "rw");
                fileChannel = file.getChannel();
                lock = fileChannel.lock();
                break;
            } catch (Exception e) {
                logger.warn("get lock error :" + e.getMessage());
            } finally {
                if (lock == null) {
                    logger.warn("lock lock ...");
                }
            }
        }
    }

    @Override
    public void doEnd() {
        if (lock != null) {
            try {
                lock.release();
            } catch (IOException e) {
                logger.warn("lock release error :" + e.getMessage());
            }
        }
        if (fileChannel != null) {
            try {
                fileChannel.close();
            } catch (IOException e) {
                logger.warn("fileChannel close error :" + e.getMessage());
            }
        }
        if (file != null) {
            try {
                file.close();
            } catch (IOException e) {
                logger.warn("fileOutputStream close error :" + e.getMessage());
            }
        }
    }
}
